package com.hll.servlet;

import com.Constants;
import com.hll.model.Book;
import com.hll.model.User;
import com.hll.service.BookService;
import com.hll.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/deleteBook.action")
public class DeleteBookServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");
        String status = request.getParameter("status");

        if (StringUtil.isEmpty(status)) {
            status = "all";
        }
        String currentPage = request.getParameter("currentPage");
        if (StringUtil.isEmpty(currentPage)) {
            currentPage = "1";
        }

        int id = Integer.parseInt(idStr);
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute(Constants.USER);

        BookService bookService = new BookService();
        Book book = bookService.getById(id);
        String redirectUrl = request.getContextPath() + "/myBook.action?status=" + status + "&currentPage=" + currentPage;

        //不一样就是不是自己的书籍
        if (book.getOwnerId() != user.getId()) {
            session.setAttribute(Constants.ERROR_FLASH_MESSAGE, "当前没有权限删除此书籍");
            response.sendRedirect(request.getContextPath() + "/myBook.action?status=" + status + "&currentPage=" + currentPage);
            return;
        }
        //不相等就是已经借出去了
        if (book.getOwnerId() != book.getCurrentOwnerId()) {
            session.setAttribute(Constants.ERROR_FLASH_MESSAGE, "当前书籍已借出，不能删除");
            response.sendRedirect(redirectUrl);
            return;
        }

        bookService.deleteById(id);
        session.setAttribute(Constants.SUCCESS_FLASH_MESSAGE, "删除书籍成功");
        response.sendRedirect(request.getContextPath() + "/myBook.action?status=" + status + "&currentPage=" + currentPage);
    }
}
